<template>
  <div class="settings-page">
    <!-- Header -->
    <van-nav-bar title="Settings" left-text="Back" left-arrow @click-left="$router.back()" fixed placeholder />

    <div class="settings-content">
      <!-- Account Settings -->
      <div class="settings-section">
        <h3 class="section-title">Account</h3>
        <van-cell-group inset>
          <van-cell title="Edit Profile" icon="edit" is-link @click="goToEditProfile" />
          <van-cell title="Change Password" icon="lock" is-link @click="showChangePasswordModal = true" />
          <van-cell title="Email Settings" icon="envelop-o" is-link @click="goToEmailSettings" />
          <van-cell title="Privacy Settings" icon="shield-o" is-link @click="goToPrivacySettings" />
        </van-cell-group>
      </div>

      <!-- Notification Settings -->
      <div class="settings-section">
        <h3 class="section-title">Notifications</h3>
        <van-cell-group inset>
          <van-cell title="Push Notifications" icon="bell-o">
            <template #right-icon>
              <van-switch v-model="settings.notifications.push" @change="updateNotificationSettings" />
            </template>
          </van-cell>
          <van-cell title="Email Notifications" icon="envelop-o">
            <template #right-icon>
              <van-switch v-model="settings.notifications.email" @change="updateNotificationSettings" />
            </template>
          </van-cell>
          <van-cell title="Achievement Alerts" icon="medal-o">
            <template #right-icon>
              <van-switch v-model="settings.notifications.achievement" @change="updateNotificationSettings" />
            </template>
          </van-cell>
          <van-cell title="Training Reminders" icon="clock-o">
            <template #right-icon>
              <van-switch v-model="settings.notifications.training" @change="updateNotificationSettings" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- Training Settings -->
      <div class="settings-section">
        <h3 class="section-title">Training Preferences</h3>
        <van-cell-group inset>
          <van-cell title="Default Difficulty" icon="chart-trending-o" is-link
            :value="difficultyLabels[settings.training.defaultDifficulty]" @click="showDifficultyPicker = true" />
          <van-cell title="Voice Feedback" icon="volume-o">
            <template #right-icon>
              <van-switch v-model="settings.training.voiceEnabled" @change="updateTrainingSettings" />
            </template>
          </van-cell>
          <van-cell title="Show Hints" icon="question-o">
            <template #right-icon>
              <van-switch v-model="settings.training.hintsEnabled" @change="updateTrainingSettings" />
            </template>
          </van-cell>
          <van-cell title="Auto Save Progress" icon="success">
            <template #right-icon>
              <van-switch v-model="settings.training.autoSave" @change="updateTrainingSettings" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- Appearance Settings -->
      <div class="settings-section">
        <h3 class="section-title">Appearance</h3>
        <van-cell-group inset>
          <van-cell title="Theme" icon="photo-o" is-link :value="themeLabels[settings.theme]"
            @click="showThemePicker = true" />
          <van-cell title="Language" icon="globe-o" is-link :value="languageLabels[settings.language]"
            @click="showLanguagePicker = true" />
          <van-cell title="Font Size" icon="font-o" is-link :value="fontSizeLabels[settings.accessibility.fontSize]"
            @click="showFontSizePicker = true" />
        </van-cell-group>
      </div>

      <!-- Privacy Settings -->
      <div class="settings-section">
        <h3 class="section-title">Privacy</h3>
        <van-cell-group inset>
          <van-cell title="Profile Visibility" icon="eye-o">
            <template #right-icon>
              <van-switch v-model="settings.privacy.profileVisible" @change="updatePrivacySettings" />
            </template>
          </van-cell>
          <van-cell title="Training History Visible" icon="clock-o">
            <template #right-icon>
              <van-switch v-model="settings.privacy.trainingHistoryVisible" @change="updatePrivacySettings" />
            </template>
          </van-cell>
          <van-cell title="Allow Friend Requests" icon="friends-o">
            <template #right-icon>
              <van-switch v-model="settings.privacy.allowFriendRequests" @change="updatePrivacySettings" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- Support & About -->
      <div class="settings-section">
        <h3 class="section-title">Support & About</h3>
        <van-cell-group inset>
          <van-cell title="Help Center" icon="question-o" is-link @click="goToHelp" />
          <van-cell title="Contact Support" icon="service-o" is-link @click="contactSupport" />
          <van-cell title="Privacy Policy" icon="description" is-link @click="goToPrivacyPolicy" />
          <van-cell title="Terms of Service" icon="notes-o" is-link @click="goToTerms" />
          <van-cell title="About Social Dojo" icon="info-o" is-link @click="goToAbout" />
        </van-cell-group>
      </div>

      <!-- Danger Zone -->
      <div class="settings-section">
        <h3 class="section-title danger">Danger Zone</h3>
        <van-cell-group inset>
          <van-cell title="Delete Account" icon="delete-o" is-link class="danger-cell"
            @click="showDeleteAccountModal = true" />
        </van-cell-group>
      </div>
    </div>

    <!-- Change Password Modal -->
    <van-popup v-model="showChangePasswordModal" position="bottom" :style="{ height: '60%' }">
      <div class="change-password-modal">
        <div class="modal-header">
          <h3>Change Password</h3>
          <van-button size="small" @click="showChangePasswordModal = false">Cancel</van-button>
        </div>
        <div class="modal-content">
          <van-form @submit="handleChangePassword">
            <div class="form-fields">
              <!-- Current Password Field -->
              <div class="field-group">
                <label class="field-label">Current Password</label>
                <van-field v-model="passwordForm.currentPassword" type="password" placeholder="Enter current password"
                  :rules="[{ required: true, message: 'Current password is required' }]" clearable
                  class="custom-field" />
              </div>

              <!-- New Password Field -->
              <div class="field-group">
                <label class="field-label">New Password</label>
                <van-field v-model="passwordForm.newPassword" type="password" placeholder="Enter new password"
                  :rules="[{ required: true, message: 'New password is required' }]" clearable class="custom-field"
                  @input="checkNewPasswordStrength" />

                <!-- Password Strength Indicator -->
                <div v-if="passwordForm.newPassword" class="password-strength">
                  <div class="strength-bar">
                    <div class="strength-fill" :class="passwordStrength.strength"
                      :style="{ width: getStrengthWidth() }">
                    </div>
                  </div>
                  <div class="strength-text">
                    Password strength: {{ passwordStrength.strength }}
                  </div>
                </div>
              </div>

              <!-- Confirm Password Field -->
              <div class="field-group">
                <label class="field-label">Confirm Password</label>
                <van-field v-model="passwordForm.confirmPassword" type="password" placeholder="Confirm new password"
                  :rules="[
                    { required: true, message: 'Password confirmation is required' },
                    { validator: validatePasswordMatch, message: 'Passwords do not match' }
                  ]" clearable class="custom-field" />
              </div>
            </div>

            <div class="modal-actions">
              <van-button type="primary" block round native-type="submit" :loading="passwordLoading">
                Change Password
              </van-button>
            </div>
          </van-form>
        </div>
      </div>
    </van-popup>

    <!-- Difficulty Picker -->
    <van-popup v-model="showDifficultyPicker" position="bottom">
      <van-picker :columns="difficultyColumns" @confirm="onDifficultyConfirm" @cancel="showDifficultyPicker = false" />
    </van-popup>

    <!-- Theme Picker -->
    <van-popup v-model="showThemePicker" position="bottom">
      <van-picker :columns="themeColumns" @confirm="onThemeConfirm" @cancel="showThemePicker = false" />
    </van-popup>

    <!-- Language Picker -->
    <van-popup v-model="showLanguagePicker" position="bottom">
      <van-picker :columns="languageColumns" @confirm="onLanguageConfirm" @cancel="showLanguagePicker = false" />
    </van-popup>

    <!-- Font Size Picker -->
    <van-popup v-model="showFontSizePicker" position="bottom">
      <van-picker :columns="fontSizeColumns" @confirm="onFontSizeConfirm" @cancel="showFontSizePicker = false" />
    </van-popup>

    <!-- Delete Account Confirmation -->
    <van-dialog v-model="showDeleteAccountModal" title="Delete Account"
      message="Are you sure you want to delete your account? This action cannot be undone." show-cancel-button
      confirm-button-text="Delete" confirm-button-color="#ee0a24" @confirm="handleDeleteAccount" />

    <!-- Support Dialog -->
    <van-dialog v-model:show="showSupportDialog" title="Contact Support" show-cancel-button
      @confirm="submitSupportRequest">
      <van-form>
        <van-field name="category" label="Category">
          <template #input>
            <van-picker :model-value="[supportForm.category]" :columns="supportCategories"
              @confirm="(value: any) => supportForm.category = value.text" />
          </template>
        </van-field>
        <van-field v-model="supportForm.subject" name="subject" label="Subject"
          placeholder="Brief description of your issue" required />
        <van-field v-model="supportForm.message" name="message" label="Message" type="textarea"
          placeholder="Please describe your issue in detail" rows="4" required />
      </van-form>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { useUserStore } from '@/stores'
import { validatePassword, validatePasswordConfirmation } from '@/utils/validate'
import type { UserPreferences, ChangePasswordData } from '@/types/user'

const router = useRouter()
// const userStore = useUserStore() // Commented out as not currently used

// Modal states
const showChangePasswordModal = ref(false)
const showDifficultyPicker = ref(false)
const showThemePicker = ref(false)
const showLanguagePicker = ref(false)
const showFontSizePicker = ref(false)
const showDeleteAccountModal = ref(false)

// Loading states
const passwordLoading = ref(false)

// Settings data
const settings = reactive<UserPreferences>({
  language: 'zh-CN',
  theme: 'light',
  notifications: {
    push: true,
    email: true,
    sms: false,
    achievement: true,
    challenge: true,
    social: true,
    training: true
  },
  privacy: {
    profileVisible: true,
    trainingHistoryVisible: true,
    achievementsVisible: true,
    allowFriendRequests: true
  },
  training: {
    defaultDifficulty: 'intermediate',
    voiceEnabled: true,
    hintsEnabled: true,
    autoSave: true
  },
  accessibility: {
    fontSize: 'medium',
    highContrast: false,
    reduceMotion: false,
    screenReader: false
  }
})

// Password form
const passwordForm = reactive<ChangePasswordData>({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordStrength = ref({
  isValid: false,
  strength: 'weak' as 'weak' | 'medium' | 'strong',
  issues: [] as string[]
})

// Labels for display
const difficultyLabels = {
  beginner: 'Beginner',
  intermediate: 'Intermediate',
  advanced: 'Advanced'
}

const themeLabels = {
  light: 'Light',
  dark: 'Dark',
  auto: 'Auto'
}

const languageLabels = {
  'zh-CN': '中文',
  'en-US': 'English'
}

const fontSizeLabels = {
  small: 'Small',
  medium: 'Medium',
  large: 'Large'
}

// Picker columns
const difficultyColumns = [
  { text: 'Beginner', value: 'beginner' },
  { text: 'Intermediate', value: 'intermediate' },
  { text: 'Advanced', value: 'advanced' }
]

const themeColumns = [
  { text: 'Light', value: 'light' },
  { text: 'Dark', value: 'dark' },
  { text: 'Auto', value: 'auto' }
]

const languageColumns = [
  { text: '中文', value: 'zh-CN' },
  { text: 'English', value: 'en-US' }
]

const fontSizeColumns = [
  { text: 'Small', value: 'small' },
  { text: 'Medium', value: 'medium' },
  { text: 'Large', value: 'large' }
]

const checkNewPasswordStrength = () => {
  if (passwordForm.newPassword) {
    passwordStrength.value = validatePassword(passwordForm.newPassword)
  }
}

const getStrengthWidth = () => {
  switch (passwordStrength.value.strength) {
    case 'weak': return '33%'
    case 'medium': return '66%'
    case 'strong': return '100%'
    default: return '0%'
  }
}

const validatePasswordMatch = (value: string) => {
  return validatePasswordConfirmation(passwordForm.newPassword, value)
}

// Navigation methods
const goToEditProfile = () => {
  router.push('/profile/edit')
}

const goToEmailSettings = () => {
  router.push('/profile/email-settings')
}

const goToPrivacySettings = () => {
  router.push('/profile/privacy-settings')
}

const goToHelp = () => {
  router.push('/help')
}

const goToPrivacyPolicy = () => {
  router.push('/privacy-policy')
}

const goToTerms = () => {
  router.push('/terms')
}

const goToAbout = () => {
  router.push('/about')
}

const showSupportDialog = ref(false)
const supportForm = reactive({
  subject: '',
  message: '',
  category: 'General'
})

const supportCategories = [
  { text: 'General', value: 'general' },
  { text: 'Technical Issue', value: 'technical' },
  { text: 'Account Problem', value: 'account' },
  { text: 'Feature Request', value: 'feature' },
  { text: 'Bug Report', value: 'bug' }
]

const contactSupport = () => {
  showSupportDialog.value = true
}

const submitSupportRequest = async () => {
  if (!supportForm.subject.trim() || !supportForm.message.trim()) {
    showToast('Please fill in all required fields')
    return
  }

  try {
    // Simulate API call
    await new Promise(resolve => setTimeout(resolve, 1000))
    showToast('Support request submitted successfully!')
    showSupportDialog.value = false
    // Reset form
    Object.assign(supportForm, {
      subject: '',
      message: '',
      category: 'General'
    })
  } catch (error) {
    showToast('Failed to submit support request')
  }
}

// Settings update methods
const updateNotificationSettings = async () => {
  try {
    // TODO: Call API to update notification settings
    showToast('Notification settings updated')
  } catch (error) {
    showToast('Failed to update settings')
  }
}

const updateTrainingSettings = async () => {
  try {
    // TODO: Call API to update training settings
    showToast('Training settings updated')
  } catch (error) {
    showToast('Failed to update settings')
  }
}

const updatePrivacySettings = async () => {
  try {
    // TODO: Call API to update privacy settings
    showToast('Privacy settings updated')
  } catch (error) {
    showToast('Failed to update settings')
  }
}

// Picker handlers
const onDifficultyConfirm = ({ selectedValues }: any) => {
  settings.training.defaultDifficulty = selectedValues[0]
  showDifficultyPicker.value = false
  updateTrainingSettings()
}

const onThemeConfirm = ({ selectedValues }: any) => {
  settings.theme = selectedValues[0]
  showThemePicker.value = false
  // TODO: Apply theme change
  showToast('Theme updated')
}

const onLanguageConfirm = ({ selectedValues }: any) => {
  settings.language = selectedValues[0]
  showLanguagePicker.value = false
  // TODO: Apply language change
  showToast('Language updated')
}

const onFontSizeConfirm = ({ selectedValues }: any) => {
  settings.accessibility.fontSize = selectedValues[0]
  showFontSizePicker.value = false
  // TODO: Apply font size change
  showToast('Font size updated')
}

// Password change
const handleChangePassword = async () => {
  try {
    passwordLoading.value = true
    // TODO: Call API to change password
    await new Promise(resolve => setTimeout(resolve, 1000)) // Mock API call

    showToast('Password changed successfully')
    showChangePasswordModal.value = false

    // Reset form
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''

  } catch (error) {
    showToast('Failed to change password')
  } finally {
    passwordLoading.value = false
  }
}

// Delete account
const handleDeleteAccount = async () => {
  try {
    // TODO: Call API to delete account
    showToast('Account deletion initiated')
    // Redirect to login or goodbye page
    router.push('/auth/login')
  } catch (error) {
    showToast('Failed to delete account')
  }
}

// Load user settings on mount
onMounted(async () => {
  try {
    // TODO: Load user preferences from API
    // const userPreferences = await userStore.fetchUserPreferences()
    // Object.assign(settings, userPreferences)
  } catch (error) {
    console.error('Failed to load user settings:', error)
  }
})
</script>

<style lang="scss" scoped>
.settings-page {
  min-height: 100vh;
  background: $background-color;
}

.settings-content {
  padding-bottom: $spacing-xl;
}

.settings-section {
  margin-bottom: $spacing-lg;

  .section-title {
    font-size: $font-size-lg;
    font-weight: $font-weight-medium;
    color: $text-color;
    padding: $spacing-md;
    margin-bottom: $spacing-xs;

    &.danger {
      color: $danger-color;
    }
  }
}

.danger-cell {
  :deep(.van-cell__title) {
    color: $danger-color;
  }

  :deep(.van-icon) {
    color: $danger-color;
  }
}

.change-password-modal {
  padding: $spacing-lg;
  height: 100%;
  display: flex;
  flex-direction: column;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-lg;
    padding-bottom: $spacing-md;
    border-bottom: 1px solid $border-color-light;

    h3 {
      font-size: $font-size-lg;
      color: $text-color;
    }
  }

  .modal-content {
    flex: 1;
    overflow-y: auto;
  }

  .modal-actions {
    margin-top: $spacing-lg;
  }
}

.password-strength {
  margin: $spacing-sm 0;
  padding: 0 $spacing-md;

  .strength-bar {
    height: 4px;
    background: $gray-3;
    border-radius: 2px;
    overflow: hidden;
    margin-bottom: $spacing-xs;

    .strength-fill {
      height: 100%;
      transition: width 0.3s ease;

      &.weak {
        background: $danger-color;
      }

      &.medium {
        background: $warning-color;
      }

      &.strong {
        background: $success-color;
      }
    }
  }

  .strength-text {
    font-size: $font-size-xs;
    color: $text-color-3;
    text-transform: capitalize;
  }
}

.form-fields {
  margin-bottom: $spacing-lg;

  .field-group {
    margin-bottom: $spacing-xl;

    .field-label {
      display: block;
      font-size: $font-size-lg;
      font-weight: $font-weight-bold;
      color: $text-color;
      margin-bottom: 8px;
    }

    .custom-field {
      :deep(.van-cell) {
        height: 46px;
        padding: 0 $spacing-md;
        background: $white;
        border: 2px solid $border-color;
        border-radius: $border-radius-md;
        box-shadow: none;
        display: flex;
        align-items: center;

        &:focus-within {
          border-color: $primary-color;
        }
      }

      :deep(.van-field__control) {
        height: 100%;
        font-size: $font-size-md;
        color: $text-color;
        line-height: 1;

        &::placeholder {
          color: $text-color-3;
        }
      }

      :deep(.van-field__label) {
        display: none;
      }

      :deep(.van-field__left-icon) {
        display: none;
      }

      :deep(.van-field__clear) {
        color: $text-color-3;
      }
    }
  }
}
</style>